package com.chinacoal.hr.levelimpl.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.chinacoal.hr.levelapi.entity.LeaveRecord;
import com.chinacoal.hr.levelimpl.dao.EmployeeDao;
import com.chinacoal.hr.levelimpl.dao.LeaveRecordDao;
import com.chinacoal.hr.levelimpl.mapper.LeaveRecordMapper;
import com.chinacoal.hr.levelimpl.param.EmployeeVO;
import com.chinacoal.hr.levelimpl.param.PositionVO;
import com.chinacoal.hr.levelimpl.service.*;
import com.chinacoal.hr.levelimpl.utils.StaticDicts;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author: YunTao.Li
 * @create: 2019-11-12 12:24
 * @description: 考勤记录service
 **/
@Service
public class LeaveRecordServiceImpl implements LeaveRecordService {

    @Resource
    private LeaveRecordMapper leaveRecordMapper;

    @Autowired
    private LeaveRecordDao leaveRecordDao;

    @Autowired
    private TransPaperDetailService transPaperDetailService;

    @Autowired
    private TransPaperDetailListService transPaperDetailListService;

    @Autowired
    private FileInfoService fileInfoService;

    @Autowired
    private WorkflowService workflowService;

    @Autowired
    private EmployeeService employeeService;

    @Autowired
    private EmployeeDao employeeDao;

    @Autowired
    private OrganizationService organizationService;


    /**
     * 获得考勤列表数据
     */
    public IPage<LeaveRecord> getLeaveRecordList(Map<String, Object> condition) {
        IPage<LeaveRecord> LeaveRecordList = this.leaveRecordDao.getLeaveRecordList(condition);
        return LeaveRecordList;
    }

    /**
     * 获得请假单明细信息
     *
     * @param condition :
     * @return : com.chinacoal.hr.levelimpl.entity.LeaveRecord
     * @author : YunTao.Li
     * @date : 2019/11/28 2019/11/28
     */
    @Override
    public LeaveRecord getLeaveRecordByCondition(Map<String, Object> condition) throws Throwable {
        LeaveRecord leaveRecord = this.leaveRecordDao.getLeaveRecord(condition);
        return leaveRecord;
    }

    /**
     * 新增请假单
     *
     * @return
     * @Auth YunTao.Li
     */
    public Map<String, String> addLeaveRecord(LeaveRecord record) {
        Map<String, String> result = new HashMap<String, String>();
        result.put("code", "-1");

        try {
            leaveRecordDao.insertLeaveRecord(record);
            String leaveId = record.getLeaveId();

            // step3 : 修改相关文件的临时paDocId为正式paDocId
            String realPaDocId = leaveId;
            String tempPaDocId = record.getFileParamPaDocId();

            fileInfoService.updatePaDocId(tempPaDocId, realPaDocId);
        } catch (Throwable e) {
            e.printStackTrace();
        }

        result.put("code", "1");
        return result;
    }

    /**
     * 编辑请假单
     *
     * @return
     * @Auth YunTao.Li
     */
    public Map<String, String> updateLeaveRecord(LeaveRecord record) {
        Map<String, String> result = new HashMap<String, String>();
        result.put("code", "-1");

        try {
            leaveRecordDao.updateLeaveRecord(record);
        } catch (Exception e) {
            e.printStackTrace();
            return result;
        }

        result.put("code", "1");
        return result;
    }

    public Map<String, String> deleteLeaveRecord(String levelId) {
        Map<String, String> result = new HashMap<String, String>();
        result.put("code", "-1");

        try {
            leaveRecordMapper.deleteById(levelId);
        } catch (Exception e) {
            e.printStackTrace();
        }

        result.put("code", "1");
        return result;
    }

    /**
     * 提交请假单
     *
     * @return
     */
    @Transactional(rollbackFor = Exception.class)   //启动事务，如果发生类型错误则回滚一下
    public Map<String, String> submitLeaveRecord(LeaveRecord record) throws Throwable {
        Map<String, String> result = new HashMap<String, String>();
        result.put("code", "-1");

        try {
            String leaveId = record.getLeaveId();
            double days = record.getDays();
            Date createDate = record.getCreationDate();
            Date startDate = record.getStartDate();
            String startTimeType = record.getStartTimeType();
            Date endDate = record.getEndDate();
            String endTimeType = record.getEndTimeType();
            String holidayType = record.getHolidayType(); //假期类别
            String paType = "1";
            String docTypeId = "e1c4b2f3-87e5-11e7-b512-7a07f6fc3890";
            String empCode = record.getEmpCode();
            String insCode = record.getInsCode();

            // 判断之前有没有创建过流程，还是撤回后再二次提交
            if (StringUtils.isBlank(insCode)) {   // 如果没有创建过流程  那么就创建一下
                String empName = record.getEmpName();
                String leaveCode = record.getLeaveCode();
                String processInstTitle = "请审批 " + empName + " 提交的编码为:" + leaveCode + "的请假单";
                // step1 : 创建并启动流程，获得processInstID
                String processInstID = workflowService.createAndStartAndFinishFirstWorkitem(WorkflowServiceImpl.PROCESSDEFNAME_LEAVE, processInstTitle, null, leaveId, record);
                record.setInsCode(processInstID); //出差申请表，记录流程实例编码
            } else {
                // step1 : 二次提交
                workflowService.createAndStartAndFinishFirstWorkitem(WorkflowServiceImpl.PROCESSDEFNAME_LEAVE, null, insCode, leaveId, record);
            }


            // step2 : 首先，将请假单的状态改为C，已提交
            record.setBusinessStatus(StaticDicts.BUSINESS_STATUS_SUBMITTED);

            // step3 : 更新请假单表,
            leaveRecordMapper.updateById(record);

            // step4 : 创建员工事务天数统计明细表   处理之后加入到员工事务天数统计明细表(xip_hr_pa_dtl)
            this.transPaperDetailService.submitTransPaperDetail(leaveId, empCode, createDate, holidayType, String.valueOf(days));

            // step5 : 员工事务单汇总表,按天数循环，每天一条记录 处理之后加入到员工事务单汇总表(xip_hr_pa_list)
            paType = StaticDicts.getPATypeByHolidayType(holidayType);   //  获得假期类别
            this.transPaperDetailListService.submitTransPaperDetailList(leaveId, docTypeId, paType, empCode, startDate, startTimeType, endDate, endTimeType, paType);

        } catch (Throwable e) {
            e.printStackTrace();
            throw e;
//            result.put("code", "1");
//            return result;
        }

        result.put("code", "1");
        return result;
    }

    /**
     * 撤回请假单
     *
     * @param leave :
     * @return : java.util.Map<java.lang.String,java.lang.String>
     * @author : YunTao.Li
     * @date : 2019/12/12 2019/12/12
     */
    @Override
    @Transactional
    public Map<String, String> drawbackLeaveRecord(LeaveRecord leave) throws Throwable {
        Map<String, String> result = new HashMap<String, String>();
        result.put("code", "-1");

        try {
            // step1 : 完成工作项,撤回
            String processInstID = leave.getInsCode();
            String leaveId = leave.getLeaveId();
            String approvalContext = "测试出差审批意见：撤回";
            workflowService.finishWorkitem(Long.parseLong(processInstID), 0, approvalContext, WorkflowServiceImpl.WORKITEM_OPCODE_DRAWBACK);

            //step3 : 修改出差申请单xip_hr_biz_travel的审批状态BUSINESS_STATUS为B已撤回
            leave.setBusinessStatus(StaticDicts.BUSINESS_STATUS_DRAWBACK);
            this.leaveRecordDao.updateLeaveRecord(leave);

            //step4 : 删除xip_hr_pa_list员工事务单汇总表的数据
            transPaperDetailListService.deleteTransPaperDetailListByDocId(leaveId);
        } catch (Throwable e) {
            e.printStackTrace();
            throw e;
        }

        result.put("code", "1");
        return result;
    }

    /**
     * 获得人员的请假数据
     *
     * @param yrmonth :
     * @param empcode :
     * @return : java.util.Map<java.lang.String,java.lang.String>
     * @author : YunTao.Li
     * @date : 2020/7/20 2020/7/20
     */
    @Override
    public Map<String, String> getYrmonthLeaveRecord(String yrmonth, String empcode) {
//        this.leaveRecordDao.leaveRecordMapper.selectLeaveDayDetail()
        return null;
    }


}
